const redisClient = require('./redis-client');
const prefix = 'MYNODEAPP'

async function cacheGet(key) {
    return await redisClient.get(`${prefix}:${key}`)
}

exports.cacheGet = cacheGet

async function cacheSet(key, value, opts) {
    await redisClient.set(`${prefix}:${key}`, value, opts)
}

exports.cacheSet = cacheSet

async function cacheSetWithExpire(key, value, expire = 10) {
    await cacheSet(key, value, {
        EX: expire
    })
}

exports.cacheSetWithExpire = cacheSetWithExpire

async function acquireLock(key, callFun) {
    const lockKey = `${prefix}:${key}`
    const reply = await redisClient.setnx(lockKey, 'locked')

    if (reply === 1) {
        try {
            await callFun()
        } catch(err) {
            throw err
        } finally {
            await redisClient.del(lockKey)
        }
    } else {
        return Promise.reject('get lock error')
    }
}

exports.cacheQcquireLock = acquireLock